<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import navbar from "@/components/navbar/navbar.vue";
import { onPageScroll } from "@dcloudio/uni-app";
import { toast } from "@/utils/tools";
import { apiPublishGoods } from "@/apis/goods";
import { apiProductDict } from "@/apis/product";
import { uploadImg } from "@/utils/request";
import { mapStores } from "pinia";
import { onLoad, onShow, onUnload } from "@dcloudio/uni-app";
import { apiProductDetails, apiProductEdit, typesInfo } from "@/apis/product";
import cache from "@/utils/cache";
import { uniChooseMedia } from "@/utils/uniToos";
import {
  commodityAddCollection,
  commodityEditCollection,
} from "@/apis/collectionCertification";

const chooseLocation = requirePlugin("chooseLocation");
const imgList = ref([]);
const videoList = ref([]);
const navbarFixed = ref(false);
const dictListArr: any = ref([]);
//const key = ref("XMGBZ-I25WB-INDUT-JPNBT-ATY6S-YRBTJ");
const key = ref("QWQBZ-XIXCZ-6W2XR-7ISUU-QQX6E-GMBEF");
const referer = ref("乐石");
const category = ref("全部,地名地址,小区,酒店宾馆");
const latitude: any = ref(null);
const longitude: any = ref(null);
const fbAddress: any = ref("");
interface Goods {
  title: "fsdfsdfs"; //标题
  describe: "sdfseeffe"; //内容
  images: "123123131"; //照片路径
  delivery: 1; //发货方式  0-包邮 1-不包邮 2-自取
  currentPrice: 123123.99; //现价
  address: "1231312232"; //详细地址
  types: 1; //类型
  brand: 1; //品牌
  fineness: 1; //成色
}
const detailId = ref(0); //商品id
const dictFields = ref([]);
const dictTypesArr = ref([]);
const data: any = reactive({
  formData: {
    id: 1, //商品id
    describes: "", // 内容
    title: "", // 标题
    images: [], // 照片路径
    delivery: 0, // 发货方式  0-包邮 1-不包邮 2-自取
    currentPrice: "", // 现价
    producingArea:"",
    types: "", // 类型
    brand: "", // 品牌
    fineness: "", // 成色
    address: "", // 详细地址
    lon: null,
    lat: null,
    dictList: [],
    leng: "", //长度
    wide: "", //宽度
    heg: "", //高度
    weight: "",
  },
  rules: {
    title: {
      type: "string",
      required: true,
      message: "请填写标题",
      trigger: ["blur", "change"],
    },
    describe: {
      type: "string",
      max: 1,
      required: true,
      message: "请填写描述",
      trigger: ["blur", "change"],
    },
  },
});

const isImg = (url = "") => {
  if (
    url.indexOf(".png") > -1 ||
    url.indexOf(".jpg") > -1 ||
    url.indexOf(".jpeg") > -1 ||
    url.indexOf(".webp") > -1
  ) {
    return true;
  }
  return false;
};

const getLimit = () => {
  if (isImg(imgList?.value?.[0])) {
    return 9;
  }

  return 1;
};

onShow(() => {
  fetchData();
  // chooseLocationFn()
  // const res = chooseLocation.getLocation();
  // console.log(res, 'res--chooseLocation.getLocation')
  // if (res) {
  //     // const {
  //     //   address,
  //     //   latitude,
  //     //   longitude,
  //     // } = res;
  //     fbAddress.value = res.address
  //     data.formData.address = res.address;
  //     console.log(data.formData.address,'data.formData.address')
  //     data.formData.lon = res.longitude
  //     data.formData.lat = res.latitude
  //     longitude.value = res.longitude;
  //     latitude.value = res.latitude;
  // }
});
const fetchData = async () => {
  chooseLocationFn();
  const res = await chooseLocation.getLocation();
  if (res) {
    fbAddress.value = res.address;
    data.formData.address = res.address;
    data.formData.lon = res.longitude;
    data.formData.lat = res.latitude;

    // data.formData.leng = res.leng;
    // data.formData.wide = res.wide;
    // data.formData.heg = res.heg;
    // data.formData.weight = res.weight;

    longitude.value = res.longitude;
    latitude.value = res.latitude;
    cache.set("address", res.address);
  }
};
onUnload(() => {
  // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
  chooseLocation.setLocation(null);
});
const chooseLocationFn = async () => {
  uni.getLocation({
    type: "wgs84",
    success: (res) => {
      latitude.value = res.latitude;
      longitude.value = res.longitude;
    },
  });
};
const formRef = ref(null);
const getDictList = async () => {
  let res = await apiProductDict({});
  dictListArr.value = res.data;
  for (const key in dictListArr.value) {
    dictFields.value.push(dictListArr.value[key]["field"]);
  }
};
const getTypesInfo = async () => {
  let res = await typesInfo();
};
const submit = () => {
  uni.showToast({
    title: "提交成功",
  });
};

const uploadImage = async () => {
  const files = (await uniChooseMedia({ mediaType: ["image"] })) as any[];
  if (imgList.value.length + files.length > 9) {
    return toast("最多允许上传九个图片!");
  }
  files.forEach(async (item: any, index: number) => {
    let resUpload = await uploadImg(item);
    imgList.value.push(resUpload.data.url);
  });
};

const uploadVideo = async () => {
  const files = (await uniChooseMedia({ mediaType: ["video"] })) as any[];
  if (files.length > 1) {
    return toast("最多允许上传一个视频!");
  }
  files.forEach(async (item: any, index: number) => {
    let resUpload = await uploadImg(item);
    videoList.value.push(resUpload.data.url);
  });
};

const getChooseLocation = async () => {
  await choosePosition();
};
const publishGoods = async () => {
  if (!data.formData.title) {
    toast("请填写标题！");
    return false;
  }

  if (!data.formData.describes) {
    toast("请填写简介！");
    return false;
  }
  if (imgList.value.length <= 0) {
    toast("请上传图片！");
    return false;
  }
  if (videoList.value.length <= 0) {
    toast("请上传视频！");
    return false;
  }

  // if (!data.formData.delivery) {
  //   toast('请选择发货方式！');
  //   return false;
  // }
  if (!data.formData.currentPrice) {
    toast("请填写价格！");
    return false;
  }
  // if (!data.formData.types) {
  //   toast('请选择类型！');
  //   return false;
  // }
  // if (!data.formData.brand) {
  //   toast('请选择品牌！');
  //   return false;
  // }
  // if (!data.formData.fineness) {
  //   toast('请选择成色！');
  //   return false;
  // }
  if (!data.formData.address) {
    toast("请选择详细地址！");
    return false;
  }
    if (!data.formData.producingArea) {
    toast("请填写产地！");
    return false;
  }
  let fieldData = [];
  // 处理字典数据
  for (const key1 in dictFields.value) {
    for (const key2 in dictListArr.value) {
      for (const key3 in dictListArr.value[key2]["types"]) {
        if (
          data.formData[dictFields.value[key1]] ==
          dictListArr.value[key2]["types"][key3]["typeId"]
        ) {
          let field = {
            field: dictFields.value[key1],
            fieldName: dictListArr.value[key2]["deptName"],
            value: data.formData[dictFields.value[key1]],
            name: dictListArr.value[key2]["types"][key3]["deptName"],
          };
          fieldData.push(field);
        }
      }
    }
  }

  data.formData.images = imgList?.value?.join(",");
  data.formData.videos = videoList?.value?.join(",");

  data.formData.dict = JSON.stringify(fieldData);

  let res = detailId.value
    ? await commodityEditCollection(data.formData)
    : await commodityAddCollection(data.formData);

  if (res.code != 200) {
    toast(res.msg);
    return false;
  }
  toast("修改成功！");
  uni.navigateBack({
    delta: 1,
  });
};

const cancelClick = () => {
  uni.navigateBack();
};

// 详情
const getDetail = async () => {
  if (!detailId.value) return;
  let res = await apiProductDetails({ id: detailId.value });
  data.formData.title = res.data.title; // 标题
  data.formData.describes = res.data.describes; // 内容
  data.formData.delivery = res.data.delivery; // 发货方式  0-包邮 1-不包邮 2-自取
  data.formData.currentPrice = res.data.currentPrice; // 现价
  // data.formData.types = res.data.types;// 类型
  data.formData.brand = res.data.brand; // 品牌
  data.formData.fineness = res.data.fineness; // 成色
  data.formData.address = res.data.address; // 详细地址
  const imgs = [...(res.data?.images?.split(",") || [])].filter(Boolean);
  const videos = [...(res.data?.videos?.split(",") || [])].filter(Boolean);
  data.formData.images = imgs; // 图片
  data.formData.videos = videos; // 视频
  imgList.value = imgs; // 图片
  videoList.value = videos; // 视频
  data.formData.dictList = JSON.parse(res.data.dict);
  let dictArr = JSON.parse(res.data.dict);
  data.formData.types = dictArr?.[0]?.value; // 类型
  data.formData.style = dictArr?.[1]?.value;
  // data.formData.type = dictArr?.[2]?.value;
  data.formData.type = dictArr?.find((o) => o.field === "type")?.value; // 种类
  data.formData.producingArea = res.data.producingArea; // 产地

  data.formData.leng = res.data.leng || "";
  data.formData.wide = res.data.wide || "";
  data.formData.heg = res.data.heg || "";
  data.formData.weight = res.data.weight || "";

};

// 地图选点
const choosePosition = async () => {
  const location = JSON.stringify({
    latitude: latitude.value,
    longitude: longitude.value,
  });
  uni.navigateTo({
    url: `plugin://chooseLocation/index?key=${key.value}&referer=${referer.value}&location=${location}&category=${category.value}`,
  });
};

const handleClose = (index: number = 0) => {
  imgList.value.splice(index, 1);
};

const handleClose1 = (index: number = 0) => {
  videoList.value.splice(index, 1);
};

// 监听页面滚动
onPageScroll((e: any) => {
  // console.log('----', e)
  // navbarFixed.value = e.scrollTop > 0 ? true : false
});

onMounted(() => {});

onLoad((options: any) => {
  detailId.value = options.id ?? "";
  data.formData.id = options.id ?? "";
  getDetail();
  getTypesInfo();
  getDictList();
  data.formData.address = cache.get("address");
});
</script>
<template>
  <!-- <navbar :fixed="navbarFixed" title="上架" /> -->
  <view class="container">
    <!-- <uv-form labelPosition="left" :model="data.formData" :rules="data.rules" ref="form"> -->
    <input
      class="form-input-item form-input-bg"
      v-model="data.formData.title"
      border="none"
      placeholder="请输入奇石描述标题~"
      :maxlength="50"
    />
    <textarea
      v-model="data.formData.describes"
      class="form-textarea-item form-input-bg"
      placeholder="请详细描述奇石信息~"
      :maxlength="500"
    />
    <view class="form-upload-card form-input-bg">
      <view class="form-upload-item">
        <text> 奇石图片</text>
      </view>
      <uv-line length="100%" color="#CECECE"></uv-line>
      <view class="form-upload">
        <view class="form-upload-img">
          <view v-for="(item, index) in imgList" :key="index" class="image">
            <image class="image" :src="item" mode="scaleToFill" />
            <view class="close flex flex-center" @click="handleClose(index)">
              <view class="close-line"></view>
            </view>
          </view>
          <view
            class="upload-btn-bg image"
            @click="uploadImage"
            v-if="imgList.length < 9"
          >
            <image
              class="icon-plus"
              src="@/static/images/plus.png"
              mode="scaleToFill"
            />
            <text class="upload-btn-text">添加图片</text>
          </view>
        </view>
      </view>
    </view>

    <view class="form-upload-card form-input-bg">
      <view class="form-upload-item">
        <text> 奇石视频 </text>
      </view>
      <uv-line length="100%" color="#CECECE"></uv-line>
      <view class="form-upload">
        <view class="form-upload-img">
          <view v-for="(item, index) in videoList" :key="index" class="image">
            <video class="image" :src="item" />
            <view class="close flex flex-center" @click="handleClose1(index)">
              <view class="close-line"></view>
            </view>
          </view>
          <view
            class="upload-btn-bg image"
            @click="uploadVideo"
            v-if="videoList.length < 1"
          >
            <image
              class="icon-plus"
              src="@/static/images/plus.png"
              mode="scaleToFill"
            />
            <text class="upload-btn-text">添加视频</text>
          </view>
        </view>
      </view>
    </view>
    <view class="form-card">
      <view class="form-card-title">
        <text>类型 / 种类</text>
      </view>
      <uv-line length="100%" color="#CECECE"></uv-line>
      <view class="form-card-title">
        <view v-for="(item, index) in dictListArr" :key="item.typeId">
          <view class="form-card-radio">
            <view class="form-radio-title">
              <text>{{ item.deptName }}:</text>
            </view>
            <view v-if="data.formData.dictList">
              <uv-radio-group v-model="data.formData[item.field]">
                <uv-radio
                  activeColor="red"
                  :label="typesItem.deptName"
                  :name="typesItem.typeId"
                  v-for="typesItem in item.types"
                  :key="typesItem.typeId"
                ></uv-radio>
              </uv-radio-group>
            </view>
          </view>
          <view class="line"></view>
        </view>
      </view>
    </view>

    <view class="line" style="margin: 0"></view>
    <view class="form-card form-item">
      <view class="form-item-label">
        <text class="padding-left">长度(cm)：</text>
      </view>
      <view class="form-input">
        <input
          type="digit"
          border="none"
          placeholder="请输入长度"
          class="form-input"
          v-model="data.formData.leng"
          :maxlength="5"
        />
        <view class="form-input-suff">
          <text></text>
        </view>
      </view>
    </view>
    <view class="form-card form-item">
      <view class="form-item-label">
        <text class="padding-left">宽度(cm)：</text>
      </view>
      <view class="form-input">
        <input
         type="digit"
          border="none"
          placeholder="请输入宽度"
          class="form-input"
          v-model="data.formData.wide"
          :maxlength="5"
        />
        <view class="form-input-suff">
          <text></text>
        </view>
      </view>
    </view>
    <view class="form-card form-item">
      <view class="form-item-label">
        <text class="padding-left">高度(cm)：</text>
      </view>
      <view class="form-input">
        <input
        type="digit"
          border="none"
          placeholder="请输入高度"
          class="form-input"
          v-model="data.formData.heg"
          :maxlength="5"
        />
        <view class="form-input-suff">
          <text></text>
        </view>
      </view>
    </view>


    <view class="form-card form-item">
      <view class="form-item-label">
        <image
          src="@/static/images/orientation.png"
          mode="scaleToFill"
          class="form-item-icon"
        />
        <text>宝贝位置：</text>
      </view>
      <view class="form-input" @click="getChooseLocation">
        <input placeholder="请选择" disabled v-model="data.formData.address" />
        <view class="form-input-suff">
          <image src="@/static/images/arrow.png" />
        </view>
      </view>
    </view>
    <view class="form-card form-item" style="margin-bottom: 0">
      <view class="form-item-label">
        <image
          src="@/static/images/orientation.png"
          mode="scaleToFill"
          class="form-item-icon"
        />
        <text>宝贝产地：</text>
      </view>
      <view class="form-input">
        <input
          type="text"
          border="none"
          class="form-input"
          v-model="data.formData.producingArea"
          placeholder="请输入宝贝产地"
        />
      </view>
    </view>
    <view class="form-card form-item" style="margin-bottom: 0">
      <view class="form-item-label">
        <image
          src="@/static/images/money.png"
          mode="scaleToFill"
          class="form-item-icon"
        />
        <text>宝贝价格：</text>
      </view>
      <view class="form-input">
        <input
          type="digit"
          border="none"
          class="form-input"
          v-model="data.formData.currentPrice"
          placeholder="请输入宝贝价格"
        />
        <view class="form-input-suff">
          <text>单位：元</text>
        </view>
      </view>
    </view>

    <view class="line" style="margin: 0"></view>
    <view class="form-card form-item">
      <view class="form-item-label">
        <image
          src="@/static/images/delivery.png"
          mode="scaleToFill"
          class="form-item-icon"
        />
        <text>发货方式：</text>
      </view>
      <uv-radio-group v-model="data.formData.delivery">
        <!-- <uv-radio activeColor="red" label="包邮" :name="0"></uv-radio>
        <uv-radio activeColor="red" label="不包邮" :name="1"></uv-radio>
        <uv-radio activeColor="red" label="自取" :name="2"></uv-radio> -->
        <uv-radio activeColor="red" label="包邮" :name="0"></uv-radio>
        <uv-radio activeColor="red" label="邮费商议" :name="1"></uv-radio>
      </uv-radio-group>
    </view>

    <view class="btn-group justify-between">
      <button class="btn-publish" @click="publishGoods">保存</button>
    </view>
  </view>
</template>
<style scoped lang="scss">
::v-deep .uv-radio {
  margin-right: 20rpx;
  margin-bottom: 20rpx;
}

.container {
  position: relative;
  margin-top: 20rpx;
  font-size: 28rpx;
  // box-sizing: border-box;

  .form-input-item {
    margin-bottom: 30rpx;
    height: 100rpx;
    padding-left: 20rpx;
  }

  textarea {
    padding: 0 20rpx;
    box-sizing: border-box;
  }

  .form-textarea-item {
    position: static;
    height: 200rpx;
    // padding: 20rpx 0 0 20rpx;
    padding-top: 20rpx;
    // padding-left: 20rpx;
    margin-bottom: 30rpx;
  }

  .form-input-bg {
    background-color: #ffffff;
    border-radius: 24rpx;
    width: 100%;
  }

  .form-upload-card {
    height: 100%;
    margin-bottom: 30rpx;

    .form-upload-item {
      padding: 20rpx;
    }

    .form-upload {
      padding: 20rpx;
      display: flex;
      height: 100%;

      .form-upload-img {
        // width: 100%;
        flex-wrap: wrap;
        // width: 100%;
        height: 100%;
        display: flex;
        // grid-template-columns: 33% 33% 33%; // justify-content: space-evenly;
        // grid-template-rows: 58%; // justify-content: space-evenly;
        // align-items: center;
      }

      .image {
        // flex-grow: 1;
        // justify-content: space-around;
        width: 144rpx;
        height: 144rpx;
        margin-right: 22rpx;
        margin-bottom: 30rpx;
        position: relative;

        .icon-plus {
          width: 48rpx;
          height: 48rpx;
        }

        image,
        video {
          width: 100%;
          height: 100%;
        }

        .close {
          position: absolute;
          right: -10rpx;
          top: -10rpx;
          background-color: #f3604e;
          width: 18px;
          height: 18px;
          border-radius: 50%;

          .close-line {
            background-color: #ffffff;
            height: 2px;
            width: 12px;
            border-radius: 1px;
          }
        }
      }

      .upload-btn-bg {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background-color: #efefef;
      }

      .upload-btn-text {
        color: #cecece;
        font-size: 24rpx;
      }
    }
  }

  .form-card {
    width: 100%;
    background-color: #ffffff;
    border-radius: 24rpx;
    margin-bottom: 20rpx;

    .form-card-title {
      color: #333333;
      padding: 20rpx;
    }

    .form-card-radio {
      display: flex;
    }
  }
}

.form-radio-title {
  font-size: 28rpx;
  margin-right: 20rpx;
}

.form-radio-group {
  padding-right: 30rpx;
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.form-radio-item {
  display: flex;
  align-items: center;

  .form-radio-label {
    font-size: 25rpx;
  }
}

.form-input {
  border: none;
  font-size: 26rpx;
  position: relative;
  width: 100%;
  flex: 1;

  .form-input-suff {
    position: absolute;
    right: 0;
    transform: translate(-50%, -50%);
    top: 50%;

    text {
      font-size: 24rpx;
      color: #bebebe;
    }

    image {
      width: 28rpx;
      height: 28rpx;
    }
  }
}

.btn-group {
  display: flex;
  padding-bottom: 60rpx;
  margin-top: 50rpx;
  font-size: 28rpx;

  .btn-cancel {
    background-color: transparent;
    border: 1px solid #999999;
    box-shadow: none;
    border-radius: 24rpx;
    width: 220rpx;
    height: 100rpx;
  }

  .btn-publish {
    // background-color: transparent;
    background: linear-gradient(
      0deg,
      rgba(191, 1, 3, 1) 0%,
      rgba(255, 84, 2, 1) 99.2%
    );
    box-shadow: none;
    border: 1px solid #999999;
    border-radius: 24rpx;
    border: none;
    // width: 420rpx;
    width: 90%;
    margin: 0 auto;
    color: #ffffff;
    height: 100rpx;
  }
}

.line {
  margin: 0;
  border-bottom-width: 1px;
  border-bottom-style: solid;
  // width: 100%;
  transform: scaleY(0.5);
  border-color: #cecece;
  margin: 10px;
}

.form-item {
  display: flex;
  height: 100rpx;
  // justify-content: center;
  align-items: center;
}

.form-item-label {
  display: flex;
  flex-direction: row;
  // width: 300rpx;
  justify-content: flex-start; // 靠左对齐
  flex-wrap: nowrap;
  // flex: 1;

  text {
    font-size: 28rpx;
  }

  .padding-left {
    padding-left: 20rpx;
  }
}

.form-item-icon {
  margin-top: 7rpx;
  width: 32rpx;
  height: 32rpx;
  margin: 0 20rpx;
}
</style>
